package com.example.network

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.util.concurrent.TimeUnit

/**
 * author：jiazhijie
 * date：2025/8/27
 * desc：
 * modify record：
 */
object BaseOkhttpClient {

    private const val BASE_URL = "http://47.99.69.231:8090"
    private const val TAG = "okhttpClient"

    private val client:OkHttpClient by lazy {
        OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build()
    }

    suspend fun postRequest(
        url:String,
        params: Map<String,String>
    ):OkhttpResponseResult<Any?>{

        return withContext(Dispatchers.IO){

            val realUrl = BASE_URL+url
            try {
                val jsonObject = JSONObject()
                params.forEach{ (key, value) ->
                    jsonObject.put(key,value)
                }

                val body = jsonObject.toString()
                    .toRequestBody("application/json".toMediaType())

                val request = Request.Builder()
                    .url(realUrl)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build()

                val response = client.newCall(request).execute()
                val responseData = response.body?.string()

                Log.i(TAG, "body is $params")
                Log.i(TAG, "response is $response")
                Log.i(TAG, "responseData is $responseData")

                if (responseData != null && response.isSuccessful) {
                    OkhttpResponseResult.Success(responseData)
                } else {
                    OkhttpResponseResult.Error(null)
                }

            }catch (e:Exception){
                Log.i(TAG,"responseData error is ${e.message}")
                OkhttpResponseResult.Error(null)
            }
        }
    }

    suspend fun getRequest(url:String):OkhttpResponseResult<String?>{

        return withContext(Dispatchers.IO){
            try {
                val realUrl = BASE_URL+url

                val request = Request.Builder()
                    .url(realUrl)
                    .get()
                    .build()

                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                Log.i(TAG,"response is $response")
                Log.i(TAG,"responseData is $responseData")

                if (responseData != null && response.isSuccessful) {
                    OkhttpResponseResult.Success(responseData)

                }else{
                    OkhttpResponseResult.Error("请求失败：$response")
                }

            }catch (e:Exception){
                Log.i(TAG,"responseData error is ${e.message}")
                OkhttpResponseResult.Error("请求失败：${e.message}")

            }
        }

    }


    /**
     * 网络请求结果密封类
     */
    sealed class OkhttpResponseResult<out T> {
        data class Success<out T>(val data: T) : OkhttpResponseResult<T>()
        data class Error(val message: String?) : OkhttpResponseResult<Nothing>()
    }



}